//公共方法
var Vue = require('vue');
function get(url,param = '',callBack,failBack=null) { 
  let sessionId = getCookie('sessionId')
  url = `${param}`?`${url}${param}`:url;
  // for(let item in query){
  //     url = `${url}?${item}=${query[item]}`;
  // }
  Vue.default.http.get(url,{headers:{'sessionId':sessionId||''},emulateJSON: true}).then(res => {
    callBack(res.body)
 }, res => {
     if(failBack){
         failBack(res.body)
     }
 });
}

function login(url,param = '',callBack,failBack=null) { 
  let sessionId = getCookie('sessionId')
  url = `${param}`?`${url}${param}`:url;
  // for(let item in query){
  //     url = `${url}?${item}=${query[item]}`;
  // }
  Vue.default.http.get(url,{emulateJSON: true}).then(res => {
    callBack(res.body)
 }, res => {
     if(failBack){
         failBack(res.body)
     }
 });
}


function deleteRequest(url,param = '',callBack,failBack=null){
  let sessionId = getCookie('sessionId');
  url = `${param}`?`${url}${param}`:url;
  Vue.default.http.delete(url,{headers:{'sessionId':sessionId},emulateJSON: true}).then(res => {
    callBack(res.data)
  }, res => {
    if (failBack) {
      failBack(res.data)
    }
  });
}


function post(url,param,callBack,failBack=null) {
  let sessionId = getCookie('sessionId');
  if (url.substr(url.length-1,1) == '/') {
    url = `${param}`?`${url}${param}`:url;
    param = ''
  } else {
    for (let item in param) {
      if (!param[item] && param[item] !== false) {
        delete param[item]
      }
    }
  }

  Vue.default.http.post(url,JSON.stringify(param),{headers:{'sessionId':sessionId},emulateJSON: true}).then(res => {
    callBack(res.body)
  }, res => {
      if(failBack){
          failBack(res.body)
      }
  });
}

function uploadFile(url,param,contentType,callBack,failBack=null) {   // 上传图片到阿里云 / 腾讯云
  let sessionId = getCookie('sessionId');
	Vue.default.http.put(url, param, {headers:{'Content-Type':contentType,'sessionId':sessionId},emulateJSON: false}).then(res => {
		callBack(res.data)
}, res => {
		if(failBack){
			failBack(res.data)
		}
	});
}

function formPost(url,param,callBack,failBack=null) {
  let sessionId = getCookie('sessionId');

  if (url.substr(url.length-1,1) == '/') {
    url = `${param}`?`${url}${param}`:url;
    param = ''
  } else {
    for (let item in param) {
      if (!param[item] && param[item] !== false) {
        delete param[item]
      }
    }
  }

  Vue.default.http.post(url,param,{headers:{'content-type': 'application/x-www-form-urlencoded','sessionId':sessionId},emulateJSON: true,credentials: true}).then(res => {
    callBack(res.body)
  }, res => {
      if(failBack){
          failBack(res.body)
      }
  });
}

function dateFormate(num, type = 'date') {
  var d = new Date(num);
  var year = d.getFullYear();
  var day = d.getDate();
  var month = +d.getMonth() + 1;
  var hour = d.getHours();
  var minute = d.getMinutes();
  var second = d.getSeconds();
  if (type == 'date') {
    var f = year + "-" + formate(month) + "-" + formate(day) + " " + formate(hour) + ":" + formate(minute) + ":" + formate(second);
  } else if (type == 'birth') {
    var f = year + "-" + formate(month) + "-" + formate(day)
  }

  function formate(d) {
    return d > 9 ? d : '0' + d;
  }
  return f;
}

function timeStampToDate(timestamp) {
  var enMonthList = ["Jan", 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec']
  var date = new Date(timestamp * 1000),
    y = date.getFullYear(),
    m = date.getMonth(),
    d = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()

  return enMonthList[m] + " " + d + ", " + y
}

//设置cookie1：
function setCookie(name, value,time) {
  let Days = 1;
  exp = new Date();
  if(time){
    exp.setTime(exp.getTime() + time* 60 * 1000);
  }else{
    exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
  }
  document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString();
}

//读取cookie：
function getCookie(name) {
  var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
  return (arr = document.cookie.match(reg)) ? unescape(arr[2]) : null;
}

//判断ios
function isIOS() {
  let isIphone = navigator.userAgent.includes('iPhone')
  let isIpad = navigator.userAgent.includes('iPad')
  return isIphone || isIpad
}

/**
 * 设置微信网页标题
 * @param {number | string } title 你要设置的标题
 */
function setPageTitle(title) {
  document.title = title
  var mobile = navigator.userAgent.toLowerCase()
  if (/iphone|ipad|ipod/.test(mobile)) {
    var iframe = document.createElement('iframe')
    iframe.style.display = 'none'
    // 替换成站标favicon路径或者任意存在的较小的图片即可
    iframe.setAttribute('src', '/favicon.ico')
    var iframeCallback = function () {
      setTimeout(function () {
        iframe.removeEventListener('load', iframeCallback)
        document.body.removeChild(iframe)
      }, 0)
    }
    iframe.addEventListener('load', iframeCallback)
    document.body.appendChild(iframe)
  }
}
module.exports = {
  post,
  get,
  dateFormate,
  timeStampToDate,
  setCookie,
  getCookie,
  setPageTitle,
  isIOS,
  deleteRequest,
  uploadFile,
  login,
  formPost
}
